package com.wstro.service.impl;

import com.wstro.entity.MaterialEntity;
import com.wstro.model.Material;
import com.wstro.model.MaterialParam;
import com.wstro.model.WechatTokenModel;
import com.wstro.service.WechatTaskService;
import com.wstro.util.DateUtils;
import com.wstro.util.HttpRequestUtil;
import com.wstro.util.JoeyUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 创建者 haogm
 * 作者 haogm
 * 描述:
 * 版权：
 * 路径: wstro-com.wstro.service.impl-WechatTaskServiceImpl
 * 创建日期: 2021/8/12 20:48
 * 版本: V1.0
 */
@Service
public class WechatTaskServiceImpl implements WechatTaskService {
    private static final String ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private final static String MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";

    @Override
    public WechatTokenModel getWechatToken(String appId, String appSecret) {
        WechatTokenModel token = new WechatTokenModel();

        String requestUrl = ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", appSecret);
        JSONObject json = HttpRequestUtil.httpsRequest(requestUrl, "GET", null);
        //判断json是否为空
        if (json != null) {
            try {

                if (json.getString("access_token") != null && json.getString("access_token") != "") {
                    //将获取的access_token放入accessToken对象中
                    token.setAccess_token(json.getString("access_token"));
                    //将获取的expires_in时间放入accessToken对象中
                    token.setExpires_in(json.getInt("expires_in"));

                } else {
                    token.setErrmsg(json.getString("errmsg"));
                    token.setErrcode(json.getString("errcode"));
                }

            } catch (Exception e) {
                token = null;
                e.printStackTrace();
                System.out.println("系统异常！");
            }
        } else {
            token = null;
        }
        return token;
    }


    /**
     * 获取素材列表并存入集合中
     *
     * @param accessToken 获取接口凭证的唯一标识
     * @param type        素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
     * @param offset      从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @param count       返回素材的数量，取值在1到20之间
     * @return
     */
    @Override
    public List<MaterialEntity> getMaterial(String accessToken, String type, int offset, int count) {
        //定义图文素材实体类集合
        List<MaterialEntity> lists = new ArrayList<MaterialEntity>();
        String outputStr = "";
        String requestUrl = MATERIAL.replace("ACCESS_TOKEN", accessToken);
        MaterialParam para = new MaterialParam();
        para.setType(type);
        para.setOffset(offset);
        para.setCount(count);
        JSONObject jsonObject = JSONObject.fromObject(para);
        outputStr = jsonObject.toString();
        //发送https请求(请求的路径,方式,所携带的参数)
        jsonObject = HttpRequestUtil.httpsRequest(requestUrl, "POST", outputStr);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                JSONArray jsonArray = jsonObject.getJSONArray("item");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject json = (JSONObject) jsonArray.get(i);
                    json = json.getJSONObject("content");
                    System.out.println(json);

                    JSONArray arr = json.getJSONArray("news_item");
                    json = (JSONObject) arr.get(0);

                    MaterialEntity material = new MaterialEntity();
                    String title = json.getString("title");
                    String author = json.getString("author");
                    String digest = json.getString("digest");
                    String thumb_media_id = json.getString("thumb_media_id");
                    String url = json.getString("url");
                    String content = json.getString("content");
                    String thumb_url=json.getString("thumb_url");
                    material.setTitle(title);
                    material.setAuthor(author);
                    material.setDigest(digest);
                    material.setThumb_media_id(thumb_media_id);
                    material.setUrl(url);
                    material.setContent(content);
                    material.setShow_cover_pic(1);
                    material.setThumbUrl(thumb_url);
                    material.setCreateTime(JoeyUtil.stampDate(new Date(), DateUtils.DATE_TIME_PATTERN));
                    lists.add(material);
                }
            } catch (Exception e) {
                accessToken = null;
                // 获取Material失败
                System.out.println("获取Material失败！");
            }
        }
        return lists;
    }

    @Override
    public void syncWechatByDay() {

    }
}
